from forms.config import app_dist,basePath
from forms.component import 管理窗口_基类,筛选条件_窗体,导入_显示_基类
from PyQt5.QtWidgets import QApplication,QWidget,QMessageBox,QFileDialog,QAction,QLineEdit,QFrame
from PyQt5.QtGui import QDoubleValidator,QIntValidator
from PyQt5.Qt import QDate,QSizePolicy,QSize,QDateTime,QIcon,QFont,Qt
import sys,os,openpyxl,xlwt,xlrd
from forms import  质量标准
from forms.component.db import 操作_sql
from forms.component.查询_窗体 import 查询_基类_窗体
from forms.component.单击的lable控件 import MyQLabel
class 质量标准_管理_窗体(管理窗口_基类):
    def __init__(self,app=None):
        self.app = app
        super().__init__()
        self.subwindow = self.app.ui.mdiArea.addSubWindow(self)
        self.localInit()


    # def __new__(cls, *args, **kwargs):
    #     '''实现单例模式'''
    #     if not hasattr(cls,'_instance'):
    #         #_instance属性中存储的就是单例
    #         cls._instance=super().__new__(cls, *args, **kwargs)
    #     else:
    #         '''有实例的时候'''
    #         cls._instance.app.ui.mdiArea.setActiveSubWindow(cls._instance.subwindow)
    #         cls._instance.app.ui.mdiArea.closeActiveSubWindow()
    #         cls._instance.app.ui.mdiArea.removeSubWindow(cls._instance)
    #         cls._instance = super().__new__(cls, *args, **kwargs)
    #     return cls._instance
    def localInit(self):
        self.ui.toolButton_7.setVisible(False)
        self.ui.toolButton_8.setVisible(False)
    def parmsInit(self):
        self.tableName = '质量标准'

    def ShowChanged(self):
        self.show_class = self.sender().objectName()
        self.ui.label_6.setText(f'当前选择的显示类型为{self.sender().text()}')
        if self.show_class=='toolButton_7':
            self.search_text['生产属性']='生产'
        else:
            self.search_text['生产属性'] = '分包'
        self.显示查询数据()
    def SearchChanged(self):
        sql = ''
        sql = f"select * from {self.tableName} "

        self.筛选条件 = 筛选条件_窗体(sql=sql, curr_app_page=self)
        self.筛选条件.show()
    def exportTemplateFile(self):
        '''导出文件模板'''
        fileName, ok = QFileDialog.getSaveFileName(self, "文件导出",
                                                   ".././temp/{}".format(
                                                       self.windowTitle()) + QDateTime.currentDateTime().toString(
                                                       "yyyyMMddHHmmss"),
                                                   "Text Files (*.xlsx);;Text Files (*.xls)")

        if ok:

            fileds=['品名','执行标准','文件路径']
            data=[['白芍','《中国药典》2020年版一部',
                  '上传时请把本行数据删除，要完整路径，多文件用英文分号隔开'],
                  ]
            #判断文件是EXCEL xlsx 还是xls
            if os.path.splitext(fileName)[-1]=='.xlsx':
                workbook = openpyxl.Workbook(fileName)
                workbook.create_sheet(self.windowTitle())
                workbook.save(fileName)
                workbook = openpyxl.load_workbook(fileName)
                worksheet = workbook[self.windowTitle()]
                for i in range(len(fileds)):
                    worksheet.cell(1, i + 1, value=fileds[i])

                for i in range(len(data)):

                    for j in range(len(fileds)):
                        worksheet.cell(2 + i, j + 1, value=data[i][j])
                workbook.save(fileName)
            elif os.path.splitext(fileName)[-1]=='.xls':

                # 创建Workbook对象
                workbook = xlwt.Workbook()
                # 添加工作表
                worksheet = workbook.add_sheet(self.windowTitle())
                # 写入数据
                for i in range(len(fileds)):
                    worksheet.write(0, i, fileds[i])
                for i in range(len(data)):
                    for j in range(len(fileds)):
                        worksheet.write(1 + i, j , data[i][j])
                # 保存文件
                workbook.save(fileName)

            path = os.path.realpath(fileName)  # 获取的相对路径，并选中文件
            os.system(f'explorer /select,{path}')

    def importFile(self):
        '''导入文件'''
        fileName, filetype = QFileDialog.getOpenFileName(self,
                                                         "选取文件",
                                                         ".././temp/",
                                                         "Text Files (*.xlsx);;Text Files (*.xls);;All Files (*)")  # 设置文件扩展名过滤,注意用双分号间隔

        if fileName:
            fileds = ['品名','执行标准','文件路径']
            # 判断文件是EXCEL xlsx 还是xls
            if os.path.splitext(fileName)[-1] == '.xlsx':
                workbook = openpyxl.load_workbook(fileName)
                worksheet = workbook.active
                worksheet_data = worksheet[worksheet.dimensions]

                columns = [column.value for column in worksheet_data[0]]

                if fileds == columns:

                    self.基础信息导入显示 = 质量标准导入_显示_窗体(self.windowTitle(), data=worksheet_data,type='xlsx')
                    self.基础信息导入显示.show()
                else:
                    QMessageBox.information(self, '提示', '字段不匹配')
            elif os.path.splitext(fileName)[-1] == '.xls':


                # 打开文件
                workbook = xlrd.open_workbook(fileName)

                # 通过索引获取第一个工作表
                sheet = workbook.sheet_by_index(0)

                # 读取列内容
                columns = [column for column in sheet.row_values(0)]
                #获取所有行列数据
                worksheet_data=[]
                for row_idx in range(sheet.nrows):
                    # 初始化行数据列表
                    row_data = []

                    # 遍历所有列
                    for col_idx in range(sheet.ncols):
                        # 读取单元格数据，并添加到行数据列表
                        cell_value = sheet.cell_value(row_idx, col_idx)
                        row_data.append(cell_value)

                    # 添加行数据到总数据列表
                    worksheet_data.append(row_data)
                if fileds == columns:

                    self.基础信息导入显示 = 质量标准导入_显示_窗体(self.windowTitle(), data=worksheet_data,type='xls')
                    self.基础信息导入显示.show()
                else:
                    QMessageBox.information(self, '提示', '字段不匹配')
    def print_get_data(self):
        '''打印报表所需要的数据
        parms: 参数集合
        fileds: 字段集合
        subreport_parms :子报表参数集合
        subreport_fileds:子报表字段集合
        '''
        parms, fileds_items, subreport_parms, subreport_fileds_items = {}, [], {}, []
        where_筛选条件 = []
        for k, v in self.search_text.items():
            if '日期' in k:
                where_筛选条件.append(f"{k} between '{v.get('开始日期')}' and  '{v.get('结束日期')}'")
            else:
                where_筛选条件.append(f"{k} like '%%{v}%%'")
        if len(where_筛选条件):

            sql = f""" select * from  {self.tableName}  where  {' and '.join(where_筛选条件)}    """

        else:
            sql = f"""select *  from {self.tableName}  """

        bool, mesg, data, fileds = 操作_sql().query_one(sql)
        # print(bool,sql,data)
        if bool:
            for d in data:
                fileds_item = {}
                for filed, v in zip(fileds, d):
                    if v == None:
                        v = ''
                    fileds_item[filed] = v
                fileds_items.append(fileds_item)


        return parms, fileds_items, subreport_parms,subreport_fileds_items
    def New_Btn_Clicked(self):
        # print(self.windowTitle())
        self.质量标准 = 质量标准_窗体(curr_app_page=self,window_title=self.windowTitle() + '_新增',row_index=-1)
        self.质量标准.show()

    def Updata_Btn_Clicked(self):
        '''更新，检查受否存在，存在就更新'''
        if self.ui.tableWidget.currentRow()==-1:
            QMessageBox.information(self,'提示','请选中要修改的行')
        else:
            try:
                row_index=self.ui.tableWidget.item(self.ui.tableWidget.currentRow(),0).text()
                self.更新 = 质量标准_窗体(curr_app_page=self,window_title=self.windowTitle() + '_更新',row_index=row_index)
                self.更新.show()
            except:
                pass

    def Show_Btn_Clicked(self):
        if self.ui.tableWidget.currentRow()==-1:
            QMessageBox.information(self,'提示','请选中要查看的行')
        else:
            try:
                row_index=self.ui.tableWidget.item(self.ui.tableWidget.currentRow(),0).text()
                self.查看 = 质量标准_窗体(curr_app_page=self,window_title=self.windowTitle() + '_查看',row_index=row_index)
                self.查看.show()
            except:
                pass

    def Del_Btn_Clicked(self):
        '''删除 1判断是否存在，存在就删除，不存在就不能删除'''
        print(self.ui.tableWidget.currentRow())
        if self.ui.tableWidget.currentRow()!=-1:
            try:
                reply = QMessageBox.question(self, "提示", f"""真的要删除吗？\n 要删除的名称：{self.ui.tableWidget.item(self.ui.tableWidget.currentRow(),1).text()}\n执行标准：{self.ui.tableWidget.item(self.ui.tableWidget.currentRow(),2).text()}""",
                                                             QMessageBox.Yes | QMessageBox.No,
                                                             QMessageBox.No)
            except Exception as e:
                QMessageBox.information(self, "提示", f"删除失败，失败原因为：{e}")
                return
            if reply ==QMessageBox.Yes:

                sql=f"select  编号 from {self.tableName} where 编号='{self.ui.tableWidget.item(self.ui.tableWidget.currentRow(),0).text()}'"
                bool, mesg, data, fileds = 操作_sql().query_one(sql)

                if bool:
                    if len(data)==0:
                        QMessageBox.information(self, "提示", f"删除失败，失败原因为：不存在")
                    elif len(data)==1:
                        sql_all=[]
                        sql = f" delete  from {self.tableName}_附件  where 质量标准_编号='{self.ui.tableWidget.item(self.ui.tableWidget.currentRow(), 0).text()}'"
                        sql_all.append((sql, ()))
                        sql=f" delete  from {self.tableName}  where 编号='{self.ui.tableWidget.item(self.ui.tableWidget.currentRow(),0).text()}'"
                        sql_all.append((sql,()))
                        bool, mesg = 操作_sql().alt_many(sql_all)

                        if bool:

                            QMessageBox.information(self, "提示", f"删除成功")


                            self.progress_working()
                        else:
                            QMessageBox.information(self, "提示", f"删除失败，失败原因为：{mesg}")
                else:
                    QMessageBox.information(self, "提示", f"删除失败，失败原因为：{mesg}")
#
class 质量标准_窗体(QWidget):
    def __init__(self,curr_app_page, window_title, row_index):
        '''饮片物料信息_原料 '''
        super().__init__()

        self.row_index = row_index
        self.curr_app_page = curr_app_page
        self.window_title = window_title # 质量管理_饮片_取样管理_原料_新增/更新
        self.tableName = '_'.join(self.window_title.split("_")[:-1]) # 质量管理_饮片_取样管理_原料
        self.initUi()



    def initUi(self):
        '''窗口的初始化'''
        self.ui = 质量标准.Ui_Form()
        self.ui.setupUi(self)

        path = os.path.dirname(os.path.abspath("__file__"))
        self.path = path
        self.__init()
        # 更新或查看做
        if int(self.row_index) >= 0:
            self.Downlord_data_into_form()
        # # #
        # self.打印控件设置()

    def __init(self):
        '''初始化的配置'''


        #查询物料名称

        物料名称_Action = QAction(self)
        物料名称_Action.setIcon(QIcon(QIcon(os.path.join(basePath,'staticfiles','img' , 'h16.png'))))
        self.ui.lineEdit.addAction(物料名称_Action, QLineEdit.TrailingPosition)  # 将该Action放到最右边
        物料名称_Action.triggered.connect(self._lookup)
        self.ui.lineEdit.returnPressed.connect(self._lookup)

        # 上传
        def Label_单击(label, hlayout):
            label.deleteLater()
            label = MyQLabel()
            # sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
            # sizePolicy.setHorizontalStretch(2)
            # sizePolicy.setVerticalStretch(0)
            # sizePolicy.setHeightForWidth(label.sizePolicy().hasHeightForWidth())
            # label.setSizePolicy(sizePolicy)
            font = QFont()
            font.setFamily("Agency FB")
            font.setUnderline(True)
            label.setFont(font)
            label.setFrameShape(QFrame.Box)
            label.setMidLineWidth(0)
            label.setAlignment(Qt.AlignCenter)
            # label.setObjectName("label_25")
            hlayout.addWidget(label)
            return label

        self.ui.label_6 = Label_单击(self.ui.label_6, self.ui.horizontalLayout)
        self.ui.pushButton_8.clicked.connect(lambda: self._Lord_Clicked(self.ui.label_6))

        self.ui.label_6.button_clicked_signal.connect(lambda: self._Downlord_clicked(self.ui.label_6, '文件'))

        # 入库编号和单号
        self._auto_bh()
        #确认按钮
        self.ui.pushButton.clicked.connect(self.Btn_Ok_Clicked)
        #取消按钮
        self.ui.pushButton_2.clicked.connect(self.close)
        #设置窗口
        self.setWindowTitle(self.window_title)

    def _lookup(self):
        '''查询未登记质量标准的产品（品名+执行标准）
        '''

        # 正常检验请验 #  质量管理_饮片_检验管理_原料
        sql = f"""select 品名,执行标准 from 产品信息 group by 品名,执行标准
                    HAVING CONCAT(品名,执行标准) not in (select CONCAT(品名,执行标准) from 质量标准) """
        # 正常检验请验 #  质量管理_饮片_检验管理_原料sqlite
        sql = f"""select 品名,执行标准 from 产品信息 group by 品名,执行标准
                    HAVING 品名 || 执行标准 not in (select 品名 || 执行标准 from 质量标准) """

        self.查询 = 查询_基类_窗体(lineedit_text=self.ui.lineEdit.text(), sql=sql)
        self.查询.show()
        self.查询.ui.tableWidget.doubleClicked.connect(self._cx_tablewidget_DbClicked)

    def _cx_tablewidget_DbClicked(self):
        # print(self.ui.tableWidget.currentRow())
        # print(self.ui.tableWidget.horizontalHeaderItem(0).text())
        db_clicked_dist = {}
        for i in range(self.查询.ui.tableWidget.columnCount()):
            db_clicked_dist[self.查询.ui.tableWidget.horizontalHeaderItem(i).text()] = self.查询.ui.tableWidget.item(
                self.查询.ui.tableWidget.currentRow(), i).text()

        self.ui.lineEdit.setText(db_clicked_dist.get('品名'))
        self.ui.lineEdit_2.setText(db_clicked_dist.get('执行标准'))

        self.查询.close()
    def _Lord_Clicked(self, label):
        label.setText('')
        fileNames, filetype = QFileDialog.getOpenFileNames(self, "选取文件", ".././temp/",
                                                         "Text Files (*.jpg *.pdf))")  # 设置文件扩展名过滤,注意用双分号间隔
        # print(fileNames, filetype)
        for fileName in fileNames:
            if os.path.exists(fileName):
                if os.path.getsize(fileName) >= 16777215:  # 大于16M
                    QMessageBox.information(self, "提示", "上传文件大于16M,无法上传")
                    label.setText('')
                else:
                    if label.text():
                        label.setText(label.text()+';'+fileName)
                    else:
                        label.setText(fileName)
            else:
                label.setText('')

    def _Downlord_clicked(self, label, fildeName):
        paths = label.text().split(';')
        for path in paths:
            if os.path.exists(path):
                path = os.path.realpath(path)  # 获取的相对路径，并选中文件
                os.system(f'explorer /select,{path}')
            elif path:

                sql = f'select {fildeName}附件,{fildeName}名称 from {self.tableName}_附件 where 质量标准_编号="{self.ui.lineEdit_22.text()}" '
                bool, mesg, data, fileds = 操作_sql().query_one(sql)

                if bool and data:
                    for i in range(len(data)):
                        current_select_dist = {}
                        for k, v in zip(fileds, data[i]):
                            if v == None:
                                v = ''
                            current_select_dist[k] = v
                        path = os.path.join(basePath , "temp" , current_select_dist[f'{fildeName}名称'])
                        with open(path, 'wb') as file:
                            file.write(current_select_dist[f'{fildeName}附件'])
                        path = os.path.realpath(path)  # 获取的相对路径，并选中文件
                        os.system(f'explorer /select,{path}')
                break
    def Downlord_data_into_form(self):
        '''查看更新数据时显示到窗口上'''

        if '更新' in self.windowTitle() or '查看' in self.windowTitle():

            current_select_dist = {}
            sql = f"select * from {self.tableName} where 编号='{self.row_index}'"
            bool, mesg, data, fileds = 操作_sql().query_one(sql)
            if bool and data:
                for k, v in zip(fileds, data[0]):
                    if v == None:
                        v = ''
                    current_select_dist[k] = v



                self.ui.lineEdit_22.setText(str(current_select_dist.get('编号')))

                self.ui.lineEdit.setText(str(current_select_dist.get('品名')))
                self.ui.lineEdit_2.setText(str(current_select_dist.get('执行标准')))
                sql = f"select 文件名称 from {self.tableName}_附件 where 质量标准_编号='{self.row_index}'"
                bool, mesg, data, fileds = 操作_sql().query_one(sql)
                if bool and data:
                    for i in range(len(data)):
                        current_select_dist = {}
                        for k, v in zip(fileds, data[i]):
                            if v == None:
                                v = ''
                            current_select_dist[k] = v
                        if str(current_select_dist.get('文件名称')):
                            if self.ui.label_6.text():
                                self.ui.label_6.setText(self.ui.label_6.text()+';'+str(current_select_dist.get('文件名称')))

                            else:
                                self.ui.label_6.setText(str(current_select_dist.get('文件名称')))




            else:
                QMessageBox.information(self, '提示', f'查询错误。错误代码为{mesg}')
                return

    def 打印控件设置(self):
        # 打印

        self.ui.toolButton.setPopupMode(QToolButton.MenuButtonPopup)
        self.ui.toolButton.clicked.connect(self.Print_Btn_Clicked)
        toolBtnMenu = QMenu()
        item_action = toolBtnMenu.addAction(QIcon(QIcon(self.path + 'h16.png')), '打印预览', self.Print_Btn_Clicked)
        item_action.setObjectName('打印预览')
        item_action = toolBtnMenu.addAction(QIcon(QIcon(self.path + 'h28.png')), '报表设计', self.Print_Btn_Clicked)
        item_action.setObjectName('报表设计')
        item_action = toolBtnMenu.addAction(QIcon(QIcon(self.path + 'h15.png')), '新增打印样式', self.Print_Btn_Clicked)
        item_action.setObjectName('新增打印样式')
        item_action = toolBtnMenu.addAction(QIcon(QIcon(self.path + 'h29.png')), '设置默认样式', self.Print_Btn_Clicked)
        item_action.setObjectName('设置默认样式')
        item_action = toolBtnMenu.addAction(QIcon(QIcon(self.path + 'h29.png')), '删除打印样式', self.Print_Btn_Clicked)
        item_action.setObjectName('删除打印样式')
        self.ui.toolButton.setMenu(toolBtnMenu)
        # 显示所有报表样式
        filename_List, path = self.显示所有报表样式()
        # print(filename_List)
        self.ui.comboBox_3.addItems(filename_List)
        file_dir = self.tableName.split('_')
        默认样式 = self.curr_app_page.app.app_dist.get('报表默认样式')
        for fi in file_dir:
            默认样式 = 默认样式.get(fi)
        默认样式 = 默认样式.get('子报表')
        self.ui.comboBox_3.setCurrentText(默认样式)

    def 显示所有报表样式(self):
        path = os.path.dirname(os.path.abspath("__file__"))

        path = path + '\\report\\' + self.tableName.replace('_', '\\') + "\子报表\\"

        # 先判断是否为一个文件夹，然后在判断里面有多少文件

        filename_List = []
        if os.path.isdir(path):

            for pat in os.listdir(path):
                if os.path.isfile(path + pat):
                    fileName = os.path.splitext(pat)
                    if fileName[1] == '.grf':
                        filename_List.append(fileName[0])
        # self.ui.comboBox_3.addItems(filename_List)
        return filename_List, path

    def Print_Btn_Clicked(self):
        # print("ddd",self.sender().objectName())
        if self.sender().objectName() == '设置默认样式':
            file_dir = self.tableName.split('_')
            设置默认样式 = self.curr_app_page.app.app_dist['报表默认样式']
            for fi in file_dir:
                设置默认样式 = 设置默认样式[fi]

            默认样式 = self.ui.comboBox_3.currentText()
            设置默认样式['子报表'] = 默认样式

            QMessageBox.information(self, '提示', '设置成功')
        elif self.sender().objectName() == '新增打印样式':
            name, ok = QInputDialog.getText(self, '创建', '请输入创建的样式名称:')
            # print(name,ok)
            if name and ok:
                filename_List, path = self.显示所有报表样式()
                if name not in filename_List:
                    # print("创建成功",path,name)
                    if len(filename_List) != 0:
                        shutil.copy(path + filename_List[0] + '.grf', path + name + '.grf')
                        # os.startfile(path+name+'.grf')
                        os.system(f"explorer /select,{path + name + '.grf'}")
                    else:
                        path_2 = os.path.dirname(os.path.abspath("__file__")) + r'\report\空白模板.grf'
                        shutil.copy(path_2, path + name + '.grf')
                        # os.startfile(path + name + '.grf')
                        os.system(f"explorer /select,{path + name + '.grf'}")
                    self.ui.comboBox_3.addItem(name)
                else:
                    QMessageBox.information(self, '提示', '样式名称重复')
        elif self.sender().objectName() == '删除打印样式':
            name, ok = QInputDialog.getText(self, '删除', '请谨慎删除，如删除请输入删除密码',QLineEdit.Password)
            # print(name,ok)
            if name == '123' and ok:
                filename_List, path = self.显示所有报表样式()
                name = self.ui.comboBox_3.currentText()
                if name not in filename_List:
                    QMessageBox.information(self, '提示', '找不到删除文件')

                else:
                    try:
                        os.remove(path + name + '.grf')

                        self.ui.comboBox_3.removeItem(self.ui.comboBox_3.currentIndex())
                        QMessageBox.information(self, '提示', '删除成功')
                    except:
                        QMessageBox.information(self, '提示', '删除异常')
        elif self.sender().objectName() == '报表设计':

            filename_List, path = self.显示所有报表样式()
            # print(filename_List,path)
            if self.ui.comboBox_3.currentText() in filename_List:

                os.startfile(path + self.ui.comboBox_3.currentText() + '.grf')
            else:
                # print("找不到相关报表")
                QMessageBox.information(self, '提示', '找不到相关报表')
        elif self.sender().objectName() == '打印预览' or self.sender().objectName() == 'toolButton_6':
            try:
                filename_List, path = self.显示所有报表样式()
                # print(filename_List, path)
                if self.ui.comboBox_3.currentText() in filename_List:
                    path = path + self.ui.comboBox_3.currentText() + '.grf'
                    Report = client.Dispatch("gregn.GridppReport.6")  # 是com组件，engine

                    if os.path.exists(path):
                        Report.LoadFromFile(path)  # 加载打印模板
                        Report.PrepareLoadData()  # 推模式，此语句要在前面定义好，表示不用数据库的数据
                        # 创建打印数据
                        parms, fileds_items, subreport_parms, subreport_fileds_items = self.print_get_data()
                        if subreport_parms or subreport_fileds_items:
                            SubReport = Report.ControlByName("SubReport1").AsSubReport.Report  # 子报表
                            SubReport.PrepareLoadData()
                            if subreport_parms:
                                for k, v in parms.items():
                                    if v == None:
                                        v = ''
                                    SubReport.ParameterByName(k).AsString = str(v)
                            if subreport_fileds_items:
                                for subreport_fileds_item in subreport_fileds_items:
                                    SubReport.DetailGrid.Recordset.Append()  # 添加字段值的开始
                                    for k, v in subreport_fileds_item.items():
                                        if v == None:
                                            v = ''
                                        SubReport.FieldByName(k).AsString = str(v)  # 对字段赋值
                                    SubReport.DetailGrid.Recordset.Post()  # 添加字段值的结束
                        if parms or fileds_items:
                            if parms:

                                for k, v in parms.items():
                                    if v == None:
                                        v = ''

                                    Report.ParameterByName(k).AsString = str(v)
                            if fileds_items:
                                for fileds_item in fileds_items:
                                    Report.DetailGrid.Recordset.Append()  # 添加字段值的开始
                                    for k, v in fileds_item.items():
                                        if v == None:
                                            v = ''
                                        Report.FieldByName(k).AsString = str(v)  # 对字段赋值
                                    Report.DetailGrid.Recordset.Post()  # 添加字段值的结束

                        if '打印预览' in self.sender().objectName():
                            Report.PrintPreview(True)  # 打印预览
                        else:
                            Report.Print(True)  # 直接打印
                    else:
                        QMessageBox.information(self, "提示", "文件不存在，请检查打印的文件是否存在")

                else:
                    # print("找不到相关报表")
                    QMessageBox.information(self, '提示', '找不到相关报表')
            except Exception as e:
                QMessageBox.information(self, '提示', f'打印报表错误:{e}')

    def print_get_data(self):
        '''打印报表所需要的数据
        parms: 参数集合
        parms = {
            '编号': self.ui.lineEdit_22.text(),
            '单据类型': self.ui.comboBox_8.currentText(),
            '单号': self.ui.lineEdit_5.text(),
            '名称': self.ui.lineEdit.text(),}
        fileds: 字段集合
        fileds_items=[{
                        货位:xxx
                        名称:xx},{
                        货位:xxx
                        名称:xx}

        ]
        subreport_parms :子报表参数集合
        subreport_fileds:子报表字段集合
        '''
        parms, fileds_items, subreport_parms, subreport_fileds_items = {}, [], {}, []

        self._auto_bh()
        取样目的,数量_规则='',''
        if self.ui.radioButton.isChecked():
            请验类型='正常请验'
        else :
            请验类型='复检请验'
        if self.ui.radioButton_4.isChecked():
            数量_规则='扣除'
        else:
            数量_规则 = '不扣除'



        parms = {
            '编号': self.ui.lineEdit_4.text(),
            '单据类型': self.ui.comboBox_8.currentText(),
            '单号': self.ui.lineEdit_5.text(),
            '名称': self.ui.lineEdit.text(),

            '执行标准': self.ui.lineEdit_2.text(),
            '规格': self.ui.lineEdit_3.text(),

            '代码': self.ui.lineEdit_7.text(),
            '请验_编号': self.ui.lineEdit_4.text(),
            '单据日期': self.ui.dateEdit.date().toString('yyyy-MM-dd'),
            '货位入库编号':self.ui.lineEdit_6.text(),
            '产地': self.ui.lineEdit_18.text(),
            '请验数量': self.ui.lineEdit_8.text(),
            '取样数量': self.ui.lineEdit_11.text(),
            '请验日期': self.ui.dateEdit_2.date().toString('yyyy-MM-dd'),
            '单位': self.ui.lineEdit_16.text(),
            '批号': self.ui.lineEdit_19.text(),

            '取样方法': self.ui.comboBox.currentText(),
            '请验部门': self.ui.comboBox_5.currentText(),
            '取样目的':取样目的,
            '数量_规则':数量_规则,
            '取样者':self.ui.comboBox_4.currentText(),
            '状态':self.ui.comboBox_2.currentText(),
            '备注':self.ui.lineEdit_10.text()



        }

        return parms, fileds_items, subreport_parms, subreport_fileds_items




    def _校验数据合法(self):
        '''判断有没有空格'''
        if (self.ui.lineEdit.text() and self.ui.lineEdit_2.text()
        ):
            pass
        else:
            return False, '表格内容品名或执行标准未填完整'
        # 判断请验日期大于入库日期，
        if self.ui.label_6.text():
            pass
        else:
            return False, '未上传质量标准'

        return True, '成功'

    def Btn_Ok_Clicked(self):
        if '新增' in self.windowTitle():
            self._auto_bh()

            bool,mesg=self._校验数据合法()
            if bool:
                current_page_dist, current_page_dist_2 = self.字段更新()
                sql_all = []

                字段名 = str(tuple(current_page_dist.keys())).replace("'", "")
                字段数量 = len(current_page_dist)
                字段值 = tuple(current_page_dist.values())

                sql = f"insert into {self.tableName} {字段名} values ({str('%s,' * 字段数量)[:-1]})"
                sql_all.append([sql, 字段值])

                # 添加附件

                def 上传附件(path, str_1):
                    附件 = {}
                    if os.path.exists(path):
                        文件名称 = os.path.basename(path)

                        with open(path, 'rb') as fil:
                            file_1 = fil.read()
                        附件[f'{str_1}名称'] = 文件名称
                        附件[f'{str_1}附件'] = file_1
                        附件['质量标准_编号'] = current_page_dist.get('编号')
                        if len(附件.keys()) == 1:
                            字段名 = '(' + str(tuple(附件.keys())[0]).replace("'", "") + ')'
                        else:
                            字段名 = str(tuple(附件.keys())).replace("'", "")

                        字段数量 = len(附件)
                        字段值 = tuple(附件.values())
                        sql = f"insert into {self.tableName}_附件 {字段名} values ({str('%s,' * 字段数量)[:-1]})"
                        sql_all.append([sql, 字段值])

                # 上传附件
                for k, v in current_page_dist_2.items():
                    for path in v.split(';'):
                        上传附件(path, k)



                bool, mesg = 操作_sql().alt_many(sql_all)

                if bool:
                    QMessageBox.information(self, "提示", "保存成功。")

                    self.curr_app_page.progress_working()

                    self.close()
                else:
                    QMessageBox.information(self, "提示", f"写入时保存失败，失败原因为：{mesg}")
            else:
                QMessageBox.information(self, "提示", f"数据不合法{mesg}")

        elif '更新' in self.windowTitle():
            bool,mesg=self._校验数据合法()
            if bool:
                current_page_dist, current_page_dist_2 = self.字段更新()
                sql_all = []
                编号 = current_page_dist.get('编号')

                del current_page_dist['编号']


                更新字段_值 = []
                for k, v in current_page_dist.items():
                    更新字段_值.append(f"{k}='{v}'".replace('%', '%%'))  # 防止特殊符号被编译
                更新字段_值 = str(更新字段_值).replace('"', '')[1:-1]
                # print(更新字段_值)
                sql = f"update {self.tableName} set {更新字段_值} where 编号=%s"
                sql_all.append([sql, 编号])

                # 上传附件
                for k, v in current_page_dist_2.items():
                    for path in v.split(';'):
                        if os.path.exists(path):
                            sql = f"delete from {self.tableName}_附件 where 质量标准_编号=%s"
                            sql_all.append([sql, 编号])
                def 上传附件(path, str_1):
                    附件 = {}
                    if os.path.exists(path):
                        文件名称 = os.path.basename(path)

                        with open(path, 'rb') as fil:
                            file_1 = fil.read()
                        附件[f'{str_1}名称'] = 文件名称
                        附件[f'{str_1}附件'] = file_1
                        附件['质量标准_编号'] = 编号
                        if len(附件.keys()) == 1:
                            字段名 = '(' + str(tuple(附件.keys())[0]).replace("'", "") + ')'
                        else:
                            字段名 = str(tuple(附件.keys())).replace("'", "")

                        字段数量 = len(附件)
                        字段值 = tuple(附件.values())
                        sql = f"insert into {self.tableName}_附件 {字段名} values ({str('%s,' * 字段数量)[:-1]})"
                        sql_all.append([sql, 字段值])


                for k, v in current_page_dist_2.items():
                    for path in v.split(';'):
                        上传附件(path, k)


                bool, mesg = 操作_sql().alt_many(sql_all)
                # print(sql_all)
                if bool:
                    QMessageBox.information(self, "提示", "保存成功。")
                    self.curr_app_page.progress_working()
                    self.close()
                else:
                    QMessageBox.information(self, "提示", f"写入时保存失败，失败原因为：{mesg}")
            else:
                QMessageBox.information(self, "提示", f"校验失败，失败原因为：{mesg}")
        elif '查看' in self.window_title:
            QMessageBox.information(self, '提示', '你没有修改的权限')

    def _auto_bh(self):
        sql = f"select MAX(编号) from {self.tableName} "
        bool, mesg, data, fileds = 操作_sql().query_one(sql)
        if bool:
            if len(data) == 1 and data[0][0] == None:
                self.ui.lineEdit_22.setText("1")
            else:
                self.ui.lineEdit_22.setText(str(f"{data[0][0] + 1}"))
        else:
            QMessageBox.information(self, "提示", f"新增失败，失败原因为：{mesg}")



    def 字段更新(self):



        current_page_dist = {
            '编号': self.ui.lineEdit_22.text(),

            '品名': self.ui.lineEdit.text(),

            '执行标准': self.ui.lineEdit_2.text(),



        }

        current_page_dist_2 = {

            '文件': self.ui.label_6.text()
        }

        return current_page_dist, current_page_dist_2

class 质量标准导入_显示_窗体(导入_显示_基类):
    def __init__(self, window_title,data ,type):
        super().__init__( window_title,data,type)
    def insertData(self):
        '''追加模式'''
        sql_all = []
        fileds=['品名','执行标准']
        编号=0
        sql = f"select MAX(编号) from {self.tableName} "
        bool, mesg, data, fileds = 操作_sql().query_one(sql)
        if bool:
            if len(data) == 1 and data[0][0] == None:
                编号=1
            else:
                编号=int(f"{data[0][0] + 1}")
        for i in range(self.ui.tableWidget.rowCount()):
            sql = f"""insert into {self.tableName} (编号,品名,执行标准) values 
            ({编号+i},'{self.ui.tableWidget.item(i, 0).text()}','{self.ui.tableWidget.item(i, 1).text()}')"""
            sql_all.append([sql, ()])
            fileNames=self.ui.tableWidget.item(i, 2).text().split(';')
            if fileNames:
                for path in fileNames:
                    附件 = {}
                    if os.path.exists(path):
                        文件名称 = os.path.basename(path)
                        if os.path.splitext(文件名称)[-1] in ('.jpg','.pdf'):
                            with open(path, 'rb') as fil:
                                file_1 = fil.read()
                            附件[f'文件名称'] = 文件名称
                            附件[f'文件附件'] = file_1
                            附件['质量标准_编号'] = 编号+i
                            if len(附件.keys()) == 1:
                                字段名 = '(' + str(tuple(附件.keys())[0]).replace("'", "") + ')'
                            else:
                                字段名 = str(tuple(附件.keys())).replace("'", "")

                            字段数量 = len(附件)
                            字段值 = tuple(附件.values())
                            sql = f"insert into {self.tableName}_附件 {字段名} values ({str('%s,' * 字段数量)[:-1]})"
                            sql_all.append([sql, 字段值])
                        else:
                            QMessageBox.information(self, "提示",
                                                    f"写入时保存失败，失败原因为：文件格式不对{self.ui.tableWidget.item(i, 0).text()}{self.ui.tableWidget.item(i, 1).text()}")
                            return
                    else:
                        QMessageBox.information(self, "提示", f"写入时保存失败，失败原因为：未找到附件路径{self.ui.tableWidget.item(i, 0).text()}{self.ui.tableWidget.item(i, 1).text()}")
                        return
            else:
                QMessageBox.information(self, "提示", f"写入时保存失败，失败原因为：未找到附件路径{self.ui.tableWidget.item(i, 0).text()}{self.ui.tableWidget.item(i, 1).text()}")
                return



        bool, mesg = 操作_sql().alt_many(sql_all)

        if bool:
            QMessageBox.information(self, "提示", "保存成功。")
            # self.parent().deleteLater()
            self.close()
        else:
            QMessageBox.information(self, "提示", f"写入时保存失败，失败原因为：{mesg}")
    def rewriteData(self):
        sql_all = []
        reply = QMessageBox.question(self, "提示",
                                     "真的要用覆写模式吗？\n复写模式表示把之前所有的记录产品信息都删除掉不包括质量标准",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:

            sql_all.append([f'delete from {self.tableName}_附件', ()])
            sql_all.append([f'delete from {self.tableName}', ()])

            fileds = ['品名', '执行标准']
            编号 = 0
            sql = f"select MAX(编号) from {self.tableName} "
            bool, mesg, data, fileds = 操作_sql().query_one(sql)
            if bool:
                if len(data) == 1 and data[0][0] == None:
                    编号 = 1
                else:
                    编号 = int(f"{data[0][0] + 1}")
            for i in range(self.ui.tableWidget.rowCount()):
                sql = f"""insert into {self.tableName} (编号,品名,执行标准) values 
                        ({编号 + i},'{self.ui.tableWidget.item(i, 0).text()}','{self.ui.tableWidget.item(i, 1).text()}')"""
                sql_all.append([sql, ()])
                fileNames = self.ui.tableWidget.item(i, 2).text().split(';')
                if fileNames:
                    for path in fileNames:
                        附件 = {}
                        if os.path.exists(path):
                            文件名称 = os.path.basename(path)
                            if os.path.splitext(文件名称)[-1] in ('.jpg', '.pdf'):
                                with open(path, 'rb') as fil:
                                    file_1 = fil.read()
                                附件[f'文件名称'] = 文件名称
                                附件[f'文件附件'] = file_1
                                附件['质量标准_编号'] = 编号 + i
                                if len(附件.keys()) == 1:
                                    字段名 = '(' + str(tuple(附件.keys())[0]).replace("'", "") + ')'
                                else:
                                    字段名 = str(tuple(附件.keys())).replace("'", "")

                                字段数量 = len(附件)
                                字段值 = tuple(附件.values())
                                sql = f"insert into {self.tableName}_附件 {字段名} values ({str('%s,' * 字段数量)[:-1]})"
                                sql_all.append([sql, 字段值])
                            else:
                                QMessageBox.information(self, "提示",
                                                        f"写入时保存失败，失败原因为：文件格式不对{self.ui.tableWidget.item(i, 0).text()}{self.ui.tableWidget.item(i, 1).text()}")
                                return
                        else:
                            QMessageBox.information(self, "提示",
                                                    f"写入时保存失败，失败原因为：未找到附件路径{self.ui.tableWidget.item(i, 0).text()}{self.ui.tableWidget.item(i, 1).text()}")
                            return
                else:
                    QMessageBox.information(self, "提示",
                                            f"写入时保存失败，失败原因为：未找到附件路径{self.ui.tableWidget.item(i, 0).text()}{self.ui.tableWidget.item(i, 1).text()}")
                    return
            bool, mesg = 操作_sql().alt_many(sql_all)
            if bool:
                QMessageBox.information(self, "提示", "保存成功。")
                self.close()
            else:
                QMessageBox.information(self, "提示", f"写入时保存失败，失败原因为：{mesg}")
    def updateData(self):
        '''更新模式
            根据品名+批号+执行标准作为更新模式
        '''
        sql_all=[]
        fileds = ['品名', '执行标准']
        needUpdateDate=[]
        #先确认是否为更新
        for i in range(self.ui.tableWidget.rowCount()):
            sql=f"""select 编号 from 质量标准 where 品名='{self.ui.tableWidget.item(i, 0).text()}' 
            and 执行标准='{self.ui.tableWidget.item(i, 1).text()}'"""
            bool, mesg, data, fileds = 操作_sql().query_one(sql)
            if bool and data:
                needUpdateDate.append([data[0][0],self.ui.tableWidget.item(i, 0).text(),self.ui.tableWidget.item(i, 1).text()])

        编号 = 0
        sql = f"select MAX(编号) from {self.tableName} "
        bool, mesg, data, fileds = 操作_sql().query_one(sql)
        if bool:
            if len(data) == 1 and data[0][0] == None:
                编号 = 1
            else:
                编号 = int(f"{data[0][0] + 1}")
        for i in range(self.ui.tableWidget.rowCount()):
            isNeedUpdate=False
            for updateDate in needUpdateDate:
                if updateDate[1]==self.ui.tableWidget.item(i, 0).text() and updateDate[2]==self.ui.tableWidget.item(i, 1).text():
                    sql = f"delete from  {self.tableName}_附件 where 质量标准_编号='%s'"
                    sql_all.append([sql, updateDate[0]])
                    isNeedUpdate = True
                    fileNames = self.ui.tableWidget.item(i, 2).text().split(';')
                    if fileNames:
                        for path in fileNames:
                            附件 = {}
                            if os.path.exists(path):
                                文件名称 = os.path.basename(path)
                                if os.path.splitext(文件名称)[-1] in ('.jpg', '.pdf'):
                                    with open(path, 'rb') as fil:
                                        file_1 = fil.read()
                                    附件[f'文件名称'] = 文件名称
                                    附件[f'文件附件'] = file_1
                                    附件['质量标准_编号'] = updateDate[0]
                                    if len(附件.keys()) == 1:
                                        字段名 = '(' + str(tuple(附件.keys())[0]).replace("'", "") + ')'
                                    else:
                                        字段名 = str(tuple(附件.keys())).replace("'", "")

                                    字段数量 = len(附件)
                                    字段值 = tuple(附件.values())
                                    sql = f"insert into {self.tableName}_附件 {字段名} values ({str('%s,' * 字段数量)[:-1]})"
                                    sql_all.append([sql, 字段值])
                                else:
                                    QMessageBox.information(self, "提示",
                                                            f"写入时保存失败，失败原因为：文件格式不对{self.ui.tableWidget.item(i, 0).text()}{self.ui.tableWidget.item(i, 1).text()}")
                                    return
                            else:
                                QMessageBox.information(self, "提示",
                                                        f"写入时保存失败，失败原因为：未找到附件路径{self.ui.tableWidget.item(i, 0).text()}{self.ui.tableWidget.item(i, 1).text()}")
                                return
                    else:
                        QMessageBox.information(self, "提示",
                                                f"写入时保存失败，失败原因为：未找到附件路径{self.ui.tableWidget.item(i, 0).text()}{self.ui.tableWidget.item(i, 1).text()}")
                        return

            if isNeedUpdate:
                continue
            else:
                编号=编号+1

                sql = f"""insert into {self.tableName} (编号,品名,执行标准) values 
                        ({编号},'{self.ui.tableWidget.item(i, 0).text()}','{self.ui.tableWidget.item(i, 1).text()}')"""
                sql_all.append([sql, ()])
                fileNames = self.ui.tableWidget.item(i, 2).text().split(';')
                if fileNames:
                    for path in fileNames:
                        附件 = {}
                        if os.path.exists(path):
                            文件名称 = os.path.basename(path)
                            if os.path.splitext(文件名称)[-1] in ('.jpg', '.pdf'):
                                with open(path, 'rb') as fil:
                                    file_1 = fil.read()
                                附件[f'文件名称'] = 文件名称
                                附件[f'文件附件'] = file_1
                                附件['质量标准_编号'] = 编号
                                if len(附件.keys()) == 1:
                                    字段名 = '(' + str(tuple(附件.keys())[0]).replace("'", "") + ')'
                                else:
                                    字段名 = str(tuple(附件.keys())).replace("'", "")

                                字段数量 = len(附件)
                                字段值 = tuple(附件.values())
                                sql = f"insert into {self.tableName}_附件 {字段名} values ({str('%s,' * 字段数量)[:-1]})"
                                sql_all.append([sql, 字段值])
                            else:
                                QMessageBox.information(self, "提示",
                                                        f"写入时保存失败，失败原因为：文件格式不对{self.ui.tableWidget.item(i, 0).text()}{self.ui.tableWidget.item(i, 1).text()}")
                                return
                        else:
                            QMessageBox.information(self, "提示",
                                                    f"写入时保存失败，失败原因为：未找到附件路径{self.ui.tableWidget.item(i, 0).text()}{self.ui.tableWidget.item(i, 1).text()}")
                            return
                else:
                    QMessageBox.information(self, "提示",
                                            f"写入时保存失败，失败原因为：未找到附件路径{self.ui.tableWidget.item(i, 0).text()}{self.ui.tableWidget.item(i, 1).text()}")
                    return




        bool, mesg = 操作_sql().alt_many(sql_all)
        print(bool,mesg,sql_all)
        if bool:
            QMessageBox.information(self, "提示", "保存成功。")
            self.close()
            # self.parent().deleteLater()

        else:
            QMessageBox.information(self, "提示", f"写入时保存失败，失败原因为：{mesg}")
if __name__=='__main__':
    app = QApplication(sys.argv)
    主窗口 = 办公室_账户管理_窗体()
    主窗口.show()

    sys.exit(app.exec())